package JFrame;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;

import static JFrame.LoginJFrame.user;

public class TransferJFrame extends JFrame implements ActionListener {
    private JButton btnConfirm = new JButton("确认");
    private JButton btnClear = new JButton("清除");
    private JLabel outCardNumber = new JLabel("转出银行卡号：");
    private JTextField tfoutCardNumber = new JTextField("19位银行卡号", 12);
    private JLabel inCardNumber = new JLabel("转入银行卡号：");
    private JTextField tfinCardNumber = new JTextField("19位银行卡号", 12);
    private JLabel labelsum = new JLabel("转账金额：");
    private JTextField tfsum = new JTextField(6);
    private JLabel transferName = new JLabel("转账人姓名：");
    private JTextField tftranferName = new JTextField(12);
    private JTextField tfreceiveName = new JTextField(12);
    private JLabel receiveName = new JLabel("接收人姓名：");


    public TransferJFrame() {
        initializeUI();
    }

    private void initializeUI() {
        this.setName("村镇银行业务储蓄系统");
        this.setTitle("转账界面");
        this.setSize(300, 400);
        this.setAlwaysOnTop(true);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        this.setLayout(new FlowLayout());

        JPanel p1 = new JPanel();
        p1.add(outCardNumber);
        p1.add(tfoutCardNumber);

        JPanel p5 = new JPanel();
        p5.add(transferName);
        p5.add(tftranferName);


        JPanel p2 = new JPanel();
        p2.add(inCardNumber);
        p2.add(tfinCardNumber);

        JPanel p6 = new JPanel();
        p6.add(receiveName);
        p6.add(tfreceiveName);

        JPanel p3 = new JPanel();
        p3.add(labelsum);
        p3.add(tfsum);

        JPanel p4 = new JPanel();
        p4.add(btnConfirm);
        p4.add(btnClear);

        this.add(p1);
        this.add(p5);
        this.add(p2);
        this.add(p6);
        this.add(p3);
        this.add(p4);

        btnConfirm.addActionListener(this);
        btnClear.addActionListener(this);

        this.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == btnConfirm) {
            try {
                judge();
            } catch (Exception exception) {
                handleException(exception);
            }
        } else if (e.getSource() == btnClear) {
            clearFields();
        }
    }

    private void clearFields() {
        tfoutCardNumber.setText("");
        tfinCardNumber.setText("");
        tftranferName.setText("");
        tfreceiveName.setText("");
        tfsum.setText("");
    }

    private void judge() throws SQLException, ClassNotFoundException {
        String money = tfsum.getText();
        double amount;
        try {
            amount = Double.parseDouble(money);
        } catch (NumberFormatException e) {
            showErrorMessage("请输入有效的金额");
            return;
        }

        String outcard = tfoutCardNumber.getText();
        String incard = tfinCardNumber.getText();

        if (outcard.isEmpty() || incard.isEmpty()) {
            showErrorMessage("请填写所有银行卡号");
            return;
        }

        try (Connection connection = getConnection()) {
            double demandMoney = getDemandMoney(connection, outcard);
            if (demandMoney > amount) {
                executeTransfer(connection, amount, outcard, incard, demandMoney);
                updateTransfer(connection,amount,outcard,incard);
                showTransferSuccess();
            } else {
                showTransferFail();
            }
        }
    }

    //执行转账操作
    private void executeTransfer(Connection connection, double amount, String outcard, String incard, double demandMoney) throws SQLException {
        connection.setAutoCommit(false);
        try {
            updateAccountBalance(connection, outcard, demandMoney - amount);
            updateAccountBalance(connection, incard, demandMoney + amount);
            connection.commit();
        } catch (SQLException e) {
            connection.rollback();
            throw e;
        } finally {
            connection.setAutoCommit(true);
        }
    }

    //添加转账记录
    private void updateTransfer(Connection connection, double amount, String outcard, String incard) throws SQLException {
        String outname = tftranferName.getText();
        String inname = tfreceiveName.getText();
        String sql = "insert into transfer values (?,?,?,?,?) ";
        try(PreparedStatement pst = connection.prepareStatement(sql)){
            pst.setString(1,outcard);
            pst.setString(2,outname);
            pst.setString(3,inname);
            pst.setDouble(4,amount);
            pst.setString(5,incard);
            pst.executeUpdate();
        }
    }

    private double getDemandMoney(Connection connection, String card) throws SQLException {
        String sql = "SELECT demandMoney FROM user WHERE cardNumber = ?";
        try (PreparedStatement pst = connection.prepareStatement(sql)) {
            pst.setString(1, card);
            try (ResultSet rs = pst.executeQuery()) {
                if (rs.next()) {
                    return rs.getDouble("demandMoney");
                } else {
                    throw new SQLException("没有找到用户记录");
                }
            }
        }
    }

    private void updateAccountBalance(Connection connection, String card, double newBalance) throws SQLException {
        String sql = "UPDATE user SET demandMoney = ? WHERE cardNumber = ?";
        try (PreparedStatement pst = connection.prepareStatement(sql)) {
            pst.setDouble(1, newBalance);
            pst.setString(2, card);
            pst.executeUpdate();
        }

//        sql = "UPDATE demanddeposit SET money = ? WHERE card = ?";
//        try (PreparedStatement pst = connection.prepareStatement(sql)) {
//            pst.setDouble(1, newBalance);
//            pst.setString(2, card);
//            pst.executeUpdate();
//        }
    }

    private Connection getConnection() throws SQLException, ClassNotFoundException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/bank";
        String username = "root";
        String password = "20222746";
        return DriverManager.getConnection(url, username, password);
    }

    private void showTransferSuccess() {
        JOptionPane.showMessageDialog(this, "转账成功", "成功", JOptionPane.INFORMATION_MESSAGE);
        this.dispose();
    }

    private void showTransferFail() {
        JOptionPane.showMessageDialog(this, "余额不足，转账失败", "失败", JOptionPane.ERROR_MESSAGE);
    }

    private void showErrorMessage(String message) {
        JOptionPane.showMessageDialog(this, message, "错误", JOptionPane.ERROR_MESSAGE);
    }

    private void handleException(Exception e) {
        e.printStackTrace(); // 或使用日志框架
        showErrorMessage("转账失败: " + e.getMessage());
    }
}
